package com.gxgeek.springdata.domain.jdbc.dao;

import com.gxgeek.springdata.common.util.JDBCUtil;
import com.gxgeek.springdata.domain.StudentDAO;
import com.gxgeek.springdata.domain.jdbc.Student;

import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 原始JDBC 实现
 * Created by gx on 2017/4/21.
 */
public class StudentDAOImpl implements StudentDAO {
    @Override
    public List<Student> query() {
        Connection connection = null;
        PreparedStatement statement= null;
        ResultSet resultSet = null;
        String sql = "select id ,name ,age from student";
        List<Student> studentList = new ArrayList<>();
        try {

            connection = JDBCUtil.getConnection();
            statement = connection.prepareStatement(sql);
            resultSet = statement.executeQuery();
            while (resultSet.next()){
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                int age = resultSet.getInt("age");
                studentList.add(new Student(name,age,id));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.relesase(resultSet,statement,connection);
        }
            return studentList;
    }
    @Override
    public int save(Student ...students) {
        List<Student> studentList = Arrays.asList(students);
        Connection connection = null;
        PreparedStatement statement= null;
        ResultSet resultSet = null;
        int  result = 0;
        String sql = "INSERT   student (name ,age)VALUES (?,?)";
        try {
            connection = JDBCUtil.getConnection();
            statement = connection.prepareStatement(sql);
            for (Student s :studentList){
                statement.setString(1,s.getName());
                statement.setInt(2,s.getAge());
                statement.addBatch();
            }
            result = statement.executeBatch().length;
            statement.clearBatch();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.relesase(resultSet,statement,connection);
        }
        return result;
    }
}
